package com.example.backend.controller;

import com.example.backend.model.UserInfo;
import com.example.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 新增客户
     */
    @PostMapping
    public ResponseEntity<Long> addUser(@RequestBody UserInfo userInfo) {
        Long id = userService.addUser(userInfo);
        return ResponseEntity.ok(id);
    }

    /**
     * 根据ID查询客户
     */
    @GetMapping("/{id}")
    public ResponseEntity<UserInfo> getUserById(@PathVariable Long id) {
        UserInfo userInfo = userService.getUserById(id);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 更新客户信息
     */
    @PutMapping
    public ResponseEntity<Boolean> updateUser(@RequestBody UserInfo userInfo) {
        boolean result = userService.updateUser(userInfo);
        return ResponseEntity.ok(result);
    }

    /**
     * 删除客户信息
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Boolean> deleteUser(@PathVariable Long id) {
        boolean result = userService.deleteUser(id);
        return ResponseEntity.ok(result);
    }

    /**
     * 按PID精确查询
     */
    @GetMapping("/pid/{pid}")
    public ResponseEntity<UserInfo> getUserByPID(@PathVariable String pid) {
        UserInfo userInfo = userService.getUserByPID(pid);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 模糊查询（姓名/电话）
     */
    @GetMapping("/search")
    public ResponseEntity<List<UserInfo>> searchUsersByKeyword(@RequestParam String keyword) {
        List<UserInfo> userList = userService.searchUsersByKeyword(keyword);
        return ResponseEntity.ok(userList);
    }

    /**
     * 地址范围查询
     */
    @GetMapping("/address")
    public ResponseEntity<List<UserInfo>> searchUsersByAddress(@RequestParam String address) {
        List<UserInfo> userList = userService.searchUsersByAddress(address);
        return ResponseEntity.ok(userList);
    }
}